#include "Seqlish.h"

void InitSeqlish(Seqlish* p)
{
	assert(p);
	p->a = (SLDataType*)malloc(sizeof(SLDataType) * 4);
	if (p->a == NULL)
	{
		perror("malloc failed");
		exit(-1);
	}
	p->size = 0;
	p->capacity = 4;
}

void ExpSeqlish(Seqlish* p)
{
	assert(p);
	if (p->capacity == p->size)
	{
		SLDataType* ret;
		ret = (SLDataType*)realloc(p->a, sizeof(SLDataType) * p->capacity * 2);
		if (ret == NULL)
		{
			perror("realloc failed");
			exit(-1);
		}
		p->a = ret;
		p->capacity *= 2;
	}
}

void Push_Back(Seqlish* p, SLDataType a)
{
	assert(p);
	ExpSeqlish(p);
	p->a[p->size] = a;
	p->size++;
}

void Pop_Back(Seqlish* p)
{
	if (p->size == 0)
	{
		return;
	}
	p->size--;
}

void Push_Front(Seqlish* p, SLDataType a)
{
	assert(p);
	ExpSeqlish(p);
	for (int i = p->size; i > 0; i--)
	{
		p->a[i] = p->a[i - 1];
	}
	p->a[0] = a;
	p->size++;
}

void Pop_Front(Seqlish* p)
{
	assert(p);
	assert(p->size, 0);
	for (int i = 0; i < p->size - 1; i++)
	{
		p->a[i] = p->a[i + 1];
	}
	p->size--;
}

void Print(Seqlish* p)
{
	for (int i = 0; i < p->size; i++)
	{
		printf("%d ", p->a[i]);
	}
	printf("\n");
}

void Insert(Seqlish* p, int x, SLDataType a)
{
	assert(p);
	if (x > p->size || x < 0)
	{
		return;
	}
	ExpSeqlish(p);
	for (int i = p->size; i > x; i--)
	{
		p->a[i] = p->a[i - 1];
	}
	p->a[x] = a;
	p->size++;
}

void Erase(Seqlish* p, int x)
{
	assert(p);
	if (x >= p->size || x < 0)
	{
		return;
	}
	if (x == 0)
	{
		p->size--;
		return;
	}
	for (int i = x; i < p->size - 1; i++)
	{
		p->a[i] = p->a[i + 1];
	}
	p->size--;
}

void Destory(Seqlish* p)
{
	free(p->a);
	p->a = NULL;
	p->size = 0;
	p->capacity = 0;
}